package com.cetc.common.resolver;

import com.alibaba.fastjson.JSON;
import com.cetc.common.anno.CurAuthUser;
import com.cetc.common.util.MyException;
import com.cetc.entity.User;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class CurAuthUserResolver implements HandlerMethodArgumentResolver {
    private RedisTemplate redisTemplate;

    public CurAuthUserResolver(RedisTemplate redisTemplate) {
        super();
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurAuthUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

//        获取request
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
//        获取token
        String token = request.getHeader("token");
        System.out.println(token);

        if(token != null){
            Object o = redisTemplate.opsForValue().get(token);
            if(o != null){
                Map<String,Object> map = (Map<String, Object>) JSON.parse(o.toString());
                User user = new User();
                user.setUseid((Integer) map.get("userId"));
                user.setUsername(map.get("username").toString());
                return map;
            }else{
                throw new MyException("未登录");
            }
        }else{
            throw new MyException("未登录");
        }
    }
}
